<?php

namespace App\Admin\Actions\Waybill;

use Encore\Admin\Actions\Action;
use Illuminate\Http\Request;
use App\Models\Waybill;
use App\Models\Goods;

class Recosting extends Action
{
    protected $selector = '.recosting';

    public function handle(Request $request)
    {
        $count = Waybill::count();
        $page_size = 100;
        $total_page = intval(ceil($count/$page_size));
        for ($page_no=1;  $page_no<=$total_page; $page_no++)
        {
            $offset = ($page_no - 1) * $page_size;
            $list = Waybill::orderBy('id','asc')->with('goods')->offset($offset)->limit($page_size)->get();

            if($list)
            {
                foreach ($list->toArray() as $key=>$value)
                {
                    if (!$value) continue;

                    $params = [
                        'goods_price' => $value['goods']['sale_price'] * $value['goods_num'],
                        'cost_amount' => $value['goods']['cost_price'] * $value['goods_num'],
                        'profit_amount' => ($value['goods']['sale_price'] * $value['goods_num']) - ($value['goods']['cost_price'] * $value['goods_num']),
                        'status' => 1,
                        'updated_at' => date('Y-m-d H:i:s'),
                    ];

                    Waybill::where('id', $value['id'])->update($params);
                }
            }
        }

        return $this->response()->success('重算完成')->refresh();
    }

    public function html()
    {
        return <<<HTML
        <a class="btn btn-sm btn-default recosting">重算成本</a>
HTML;
    }

    public function dialog()
    {
        $this->confirm('确定重新计算所有运单吗？');
    }
}